package org.dromara.business.service.impl;

import cn.dev33.satoken.config.SaTokenConfig;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.dromara.business.domain.OrphanDetails;
import org.dromara.business.domain.User;
import org.dromara.business.domain.VolunteerDetails;
import org.dromara.business.domain.bo.UserBo;
import org.dromara.business.domain.vo.OrphanDetailsVo;
import org.dromara.business.domain.vo.UserVo;
import org.dromara.business.domain.vo.VolunteerDetailsVo;
import org.dromara.business.mapper.UserMapper;
import org.dromara.business.service.OrphanDetailsService;
import org.dromara.business.service.UserService;
import org.dromara.business.service.VolunteerDetailsService;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.enums.UserType;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import cn.hutool.core.util.StrUtil;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用户信息Service业务层处理
 *
 * @author zlj
 * @date 2024-11-19
 */
@RequiredArgsConstructor
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserMapper baseMapper;
    private final OrphanDetailsService orphanDetailsService;
    private final VolunteerDetailsService volunteerDetailsService;

    /**
     * 查询用户信息
     */
    @Override
    public UserVo queryById(Long userId) {
        return baseMapper.selectVoById(userId);
    }

    /**
     * 查询用户信息列表
     */
    @Override
    public TableDataInfo<UserVo> queryPageList(UserBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<User> lqw = buildQueryWrapper(bo);
        Page<UserVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        return TableDataInfo.build(result);
    }

    /**
     * 查询用户信息列表
     */
    @Override
    public List<UserVo> queryList(UserBo bo) {
        LambdaQueryWrapper<User> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<User> buildQueryWrapper(UserBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<User> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getDeptId() != null, User::getDeptId, bo.getDeptId());
        lqw.like(StrUtil.isNotBlank(bo.getUserName()), User::getUserName, bo.getUserName());
        lqw.like(StrUtil.isNotBlank(bo.getNickName()), User::getNickName, bo.getNickName());
        lqw.eq(StrUtil.isNotBlank(bo.getUserType()), User::getUserType, bo.getUserType());
        lqw.eq(StrUtil.isNotBlank(bo.getEmail()), User::getEmail, bo.getEmail());
        lqw.eq(StrUtil.isNotBlank(bo.getPhonenumber()), User::getPhonenumber, bo.getPhonenumber());
        lqw.eq(StrUtil.isNotBlank(bo.getOpenid()), User::getOpenid, bo.getOpenid());
        lqw.eq(StrUtil.isNotBlank(bo.getUnionid()), User::getUnionid, bo.getUnionid());
        lqw.eq(StrUtil.isNotBlank(bo.getSex()), User::getSex, bo.getSex());
        lqw.eq(bo.getAvatar() != null, User::getAvatar, bo.getAvatar());
        lqw.eq(StrUtil.isNotBlank(bo.getPassword()), User::getPassword, bo.getPassword());
        lqw.eq(bo.getAmount() != null, User::getAmount, bo.getAmount());
        lqw.eq(bo.getAllAmount() != null, User::getAllAmount, bo.getAllAmount());
        lqw.eq(StrUtil.isNotBlank(bo.getStatus()), User::getStatus, bo.getStatus());
        lqw.eq(StrUtil.isNotBlank(bo.getLoginIp()), User::getLoginIp, bo.getLoginIp());
        lqw.eq(bo.getLoginDate() != null, User::getLoginDate, bo.getLoginDate());
        lqw.eq(bo.getQrCode() != null, User::getQrCode, bo.getQrCode());
        lqw.eq(bo.getSuperiorId() != null, User::getSuperiorId, bo.getSuperiorId());
        lqw.eq(StrUtil.isNotBlank(bo.getWxAvatar()), User::getWxAvatar, bo.getWxAvatar());
        lqw.eq(StrUtil.isNotBlank(bo.getType()), User::getType, bo.getType());
        lqw.like(StrUtil.isNotBlank(bo.getName()), User::getName, bo.getName());
        lqw.orderByDesc(User::getCreateTime);
        return lqw;
    }

    /**
     * 新增用户信息
     */
    @Override
    public Boolean insertByBo(UserBo bo) {
        User add = MapstructUtils.convert(bo, User.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setUserId(add.getUserId());
        }
        return flag;
    }

    /**
     * 修改用户信息
     */
    @Override
    public Boolean updateByBo(UserBo bo) {
        User update = MapstructUtils.convert(bo, User.class);
        validEntityBeforeSave(update);
        if (LoginHelper.getUserType().getUserType().equals(UserType.XCX_USER.getUserType())) {
            update.setUserId(LoginHelper.getUserId());
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(User entity) {

    }

    /**
     * 批量删除用户信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {

        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int gqTimeUpdate(String date) {
        LocalDateTime currentTime = LocalDateTime.now();
        Long userId = LoginHelper.getUserId();
        User user = this.getById(userId);
        user.setHyNumber(user.getHyNumber()-1);
        user.setUpdateTime(new Date());

        // 注意：这里假设你有一个方法将 Date 转换为 LocalDateTime
        LocalDateTime gqTimes = convertToLocalDateTime(user.getGqTime(),currentTime);
        if ("感谢参与".equals(date)) {
            return baseMapper.updateById(user);
        }
        Integer daysToAdd = extractNumber(date);
        // 计算当前时间加上指定天数后的时间
        LocalDateTime newTime = gqTimes.plusDays(daysToAdd);
        Date gqTime = Date.from(newTime.atZone(ZoneId.systemDefault()).toInstant());
        user.setGqTime(gqTime);
        user.setVip("1");
        return baseMapper.updateById(user);
    }

    @Override
    public TableDataInfo<UserVo> getAssistedUserId(UserBo bo, PageQuery pageQuery) {
        Long userId = LoginHelper.getUserId();
        UserVo userVo = baseMapper.selectVoById(userId);

        String assistedUserId = userVo.getAssistedUserId();
        if (null == assistedUserId) {
            return null;
        }
        String[] split = assistedUserId.split(",");
        LambdaQueryWrapper<User> lqw = Wrappers.lambdaQuery();
        lqw.in(User::getUserId, split);
        Page<UserVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        List<UserVo> records = result.getRecords();
        for (UserVo record : records) {
            OrphanDetails one = orphanDetailsService.lambdaQuery().eq(OrphanDetails::getUserId, record.getUserId()).one();
            if (null != one) {
                record.setPicture(one.getPicture());
            }
        }
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<UserVo> getHelperuUserId(UserBo bo, PageQuery pageQuery) {
        Long userId = LoginHelper.getUserId();
        UserVo userVo = baseMapper.selectVoById(userId);

        String assistedUserId = userVo.getAssistedUserId();
        if (null == assistedUserId) {
            return null;
        }
        String[] split = assistedUserId.split(",");
        LambdaQueryWrapper<User> lqw = Wrappers.lambdaQuery();
        lqw.in(User::getUserId, split);
        Page<UserVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addAssistedUserId(UserBo bo) {
        Long userId = LoginHelper.getUserId();
        UserVo userVo = baseMapper.selectVoById(userId);
        String assistedUserId = userVo.getAssistedUserId();
        if (null != assistedUserId) {
            assistedUserId += ",";
        } else {
            assistedUserId = "";
        }
        userVo.setAssistedUserId(assistedUserId += bo.getUserId());
        User update = MapstructUtils.convert(userVo, User.class);
        baseMapper.updateById(update);
        boolean update2 = this.lambdaUpdate().set(User::getAssistedUserId, assistedUserId).eq(User::getUserId, userId).update();

        UserVo userVo1 = baseMapper.selectVoById(bo.getUserId());
        String helperuUserId = userVo1.getHelperuUserId();
        if (null != helperuUserId) {
            helperuUserId += ",";
        } else {
            helperuUserId = "";
        }
        helperuUserId += userId;
        boolean update1 = this.lambdaUpdate().set(User::getHelperuUserId, helperuUserId).eq(User::getUserId, bo.getUserId()).update();
        return update1 ? 1 : 0;
    }

    @Override
    public TableDataInfo<UserVo> getOrphanList(UserBo bo, PageQuery pageQuery) {
        Long userId = LoginHelper.getUserId();
        LambdaQueryWrapper<User> lqw = buildQueryWrapper(bo);
        lqw.eq(User::getType, "1");
        Page<UserVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<UserVo> records = result.getRecords();
        records.forEach(record -> {
            if (StrUtil.isNotBlank(record.getHelperuUserId())) {
                int length = record.getHelperuUserId().split(",").length;
                record.setHelpMe(length);
            } else {
                record.setHelpMe(0);
            }
            OrphanDetails one = orphanDetailsService.lambdaQuery().eq(OrphanDetails::getUserId, record.getUserId()).one();

            if (null != one) {
                record.setPicture(one.getPicture());
                record.setName(one.getName());
            }
            record.setAssistedBefore("0");
            if (StrUtil.isNotBlank(record.getHelperuUserId())) {
                if (record.getHelperuUserId().contains(userId.toString())) {
                    record.setAssistedBefore("1");
                }
            }


        });
        return TableDataInfo.build(result);


    }

    @Override
    public R<UserVo> getMyInfo(Long userId) {
        User byId = this.getById(userId);
        if (null == byId) {
            return null;
        }
        UserVo bean = BeanUtil.toBean(byId, UserVo.class);
        bean.setHelpMe(0);
        bean.setMeHelp(0);

        if (StrUtil.isNotBlank(byId.getHelperuUserId())) {
            bean.setHelpMe(byId.getHelperuUserId().split(",").length);

        }
        if (StrUtil.isNotBlank(byId.getAssistedUserId())) {
            bean.setMeHelp(byId.getAssistedUserId().split(",").length);
        }
        bean.setOrphanState("0");
        bean.setVolunteerState("0");
        VolunteerDetails one = volunteerDetailsService.lambdaQuery().eq(VolunteerDetails::getUserId, userId).one();
        if (null != one) {

            bean.setVolunteerState(one.getState());

        }

        OrphanDetails byId1 = orphanDetailsService.lambdaQuery().eq(OrphanDetails::getUserId, userId).one();
        if (null != byId1) {

            bean.setOrphanState(byId1.getState());

        }
        return R.ok(bean);
    }


    public static Integer extractNumber(String input) {
        // 定义正则表达式模式，匹配一个或多个数字
        String regex = "\\d+";

        // 编译正则表达式
        Pattern pattern = Pattern.compile(regex);

        // 创建匹配器
        Matcher matcher = pattern.matcher(input);

        if (matcher.find()) {
            // 提取并解析数字
            return Integer.parseInt(matcher.group());
        } else {
            throw new ServiceException("转盘奖品配置错误");

        }
    }

    // 辅助方法：将 Date 转换为 LocalDateTime
    private LocalDateTime convertToLocalDateTime(Date date, LocalDateTime currentTime) {
        LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

        if (localDateTime.isBefore(currentTime)) {
            return currentTime;
        } else {
            return localDateTime;
        }
    }
}
